package com.woniu.project.web.common;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

public class UploadImg {
    static String secretId = "AKIDc9QREC6c9ObXEBfeRPIuKVnqeCVb9uAC";
    static String secretKey = "ijUy7zcy2z7yYpre9MUgbFfneDWYVFix";
    static String bucketName = "klaus-1303116484";
    static String requestUrl = "https://klaus-1303116484.cos.ap-chongqing.myqcloud.com/";

    public static String upLoad(MultipartFile file) {
        if (file == null) {
            return null;
        }
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
// 2 设置 bucket 的区域, COS 地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
// clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。
        Region region = new Region("ap-chongqing");
        ClientConfig clientConfig = new ClientConfig(region);
// 3 生成 cos 客户端。
        COSClient cosClient = new COSClient(cred, clientConfig);
        String oldFileName = file.getOriginalFilename();
        String oldName = oldFileName.substring(oldFileName.lastIndexOf("."));
        String newFileName = UUID.randomUUID().toString().replace("-", "");
        // 指定要上传到 COS 上的对象键
        File localFile = null;
        try {
            localFile = File.createTempFile(newFileName, oldName);
            file.transferTo(localFile);
            // 指定要上传到 COS 上的路径
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, newFileName + oldName, localFile);
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            //返回网络路径
            return requestUrl + newFileName + oldName;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            // 关闭客户端
            cosClient.shutdown();
        }
    }
}
